package br.ufms.facom;

import java.io.IOException;
import java.util.UUID;


import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Main extends Activity {

	private BluetoothAdapter mBluetoothAdapter;

	private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
	private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
	private static final int REQUEST_ENABLE_BT = 3;

	private static final UUID MY_UUID_INSECURE = UUID.fromString("5ca233c0-2bba-11e0-ad64-0823200c9a66");


	private static final String NAME_INSECURE = "TrucoBT";

	private static AcceptThread mAcceptThread;
	private static ConnectThread mConnectThread;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);

		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
		    Toast.makeText(this, "Device does not support bluetooth", Toast.LENGTH_SHORT).show();
		}
		if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		}
	
		
	}
	
	public void callServer(View view) {
		mAcceptThread=new AcceptThread();
		mAcceptThread.start();
	}
	
	
	public void callClient(View view) {
		Intent serverIntent = new Intent(Main.this, DeviceListActivity.class);
        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(resultCode==Activity.RESULT_OK&&data!=null)
		{	String address=data.getExtras()
		        .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
			
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
			
			mConnectThread=new ConnectThread(device);
			mConnectThread.start();
			
		}

	}
	public static void stopBTThread()
	{
		if(mConnectThread!=null)mConnectThread.cancel();
		if(mAcceptThread!=null)mAcceptThread.cancel();
	}
	
	private class AcceptThread extends Thread {
	    private final BluetoothServerSocket mmServerSocket;
	 
	    public AcceptThread() {
	        BluetoothServerSocket tmp = null;
	        try {
	            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_INSECURE, MY_UUID_INSECURE);
	        } catch (IOException e) { }
	        mmServerSocket = tmp;
	    }
	 
	    public void run() {
	        BluetoothSocket socket = null;
	        while (true) {
	            try {
	                socket = mmServerSocket.accept();
	              
	                TrucoBT.setBluetoothSocket(socket);
	                
	                Intent i=new Intent(Main.this,TrucoBT.class);
	                
	                SharedPreferences previewSizePref = getSharedPreferences("PREF",MODE_PRIVATE);
		    		SharedPreferences.Editor prefEditor = previewSizePref.edit();
		    		prefEditor.putInt("server", 1);
		    		prefEditor.commit();
	                
	                finish();
	                startActivity(i);
	            } catch (IOException e) {
	                break;
	            }
	            if (socket != null) {
	                try {
						mmServerSocket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	                break;
	            }
	        }
	    }
	    public void cancel() {
	        try {
	            mmServerSocket.close();
	        } catch (IOException e) { }
	    }
	}

	private class ConnectThread extends Thread {
	    private final BluetoothSocket mmSocket;
	    private final BluetoothDevice mmDevice;
	 
	    public ConnectThread(BluetoothDevice device) {
	        BluetoothSocket tmp = null;
	        mmDevice = device;
	 
	        try {
	            tmp = device.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
	        } catch (IOException e) { }
	        mmSocket = tmp;
	    }
	 
	    public void run() {
	        mBluetoothAdapter.cancelDiscovery();
	 
	        try {
	        	mmSocket.connect();
	        
	        	TrucoBT.setBluetoothSocket(mmSocket);
	        	Intent i=new Intent(Main.this,TrucoBT.class);
	        	
	        	SharedPreferences previewSizePref = getSharedPreferences("PREF",MODE_PRIVATE);
	    		SharedPreferences.Editor prefEditor = previewSizePref.edit();
	    		prefEditor.putInt("server", 0);
	    		prefEditor.commit();
	    		
	        	finish();
	        	startActivity(i);
	            
	            
	        } catch (IOException connectException) {
	            try {
	                mmSocket.close();
	            } catch (IOException closeException) { }
	            return;
	        }
	 
	    }
	 
	    public void cancel() {
	        try {
	            mmSocket.close();
	        } catch (IOException e) { }
	    }
	}

	
}
